package com.yg.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yg.config.FilePathConfig;
import com.yg.config.exceptionhandler.YGException;
import com.yg.config.result.R;
import com.yg.config.result.ResultCode;
import com.yg.entity.readAndWriteTemplates.ResearchProjectRead;
import com.yg.entity.singleEntity.Dictionary;
import com.yg.entity.singleEntity.ResearchProject;
import com.yg.mapper.DictionaryMapper;
import com.yg.mapper.ResearchProjectMapper;
import com.yg.service.ResearchProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 对应sheet05，此表是教研项目表 服务实现类
 * </p>
 *
 * @author YingGu
 * @since 2020-11-04
 */
@Service
public class ResearchProjectServiceImpl extends ServiceImpl<ResearchProjectMapper, ResearchProject> implements ResearchProjectService {

    @Autowired
    ResearchProjectMapper researchProjectMapper;
    @Autowired
    FilePathConfig filePathConfig;
    @Autowired
    DictionaryMapper dictionaryMapper;

    /**
     * 读取excel
     * @param fileInputStream
     * @return
     */
    @Override
    public R readExcel(FileInputStream fileInputStream) {
        //创建要录入的bean的list
        List<ResearchProject> researchProjectList = new ArrayList<ResearchProject>();
        //创建R
        R r = R.getR();
        r.setCode(ResultCode.SUCCESS);
        //存储错误信息
        List<String> errorList = new ArrayList<>();

        //读取excel(匿名内部类解决传参问题)
        EasyExcel.read(fileInputStream, ResearchProjectRead.class, new AnalysisEventListener<ResearchProjectRead>() {

            //每行执行
            @Override
            public void invoke(ResearchProjectRead researchProjectRead, AnalysisContext analysisContext) {
                //创建数据库对应实体类
                ResearchProject researchProject = new ResearchProject();

                BeanUtils.copyProperties(researchProjectRead,researchProject);

                //添加进list
                researchProjectList.add(researchProject);

            }

            //所有行读完执行
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                if (r.getCode() == ResultCode.SUCCESS){
                    //向数据库插入数据
                    saveData();
                }else {
                    //添加错误信息
                    r.data("errorMsg",errorList);
                }
            }


            /**
             * 读取异常
             * @param exception
             * @param context
             * @throws Exception
             */
            @Override
            public void onException(Exception exception, AnalysisContext context) throws Exception {
                if (exception instanceof ExcelDataConvertException) {
                    ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;

                    //向errorList中添加信息
                    r.code(ResultCode.ERROR);
                    System.out.println("行："+(excelDataConvertException.getRowIndex() + 1) + "列" +(excelDataConvertException.getColumnIndex() + 1));
                    errorList.add("行："+ (excelDataConvertException.getRowIndex() + 1) + "列" +(excelDataConvertException.getColumnIndex() + 1));
//                    LOGGER.error("第{}行，第{}列解析异常", excelDataConvertException.getRowIndex(),
//                            excelDataConvertException.getColumnIndex());
                }
            }

            //存数据库操作
            private void saveData(){
                for (int i = 0; i < researchProjectList.size(); i++) {
                    try {
                        researchProjectMapper.insert(researchProjectList.get(i));
                    } catch (RuntimeException e) {
                        throw new YGException(ResultCode.INSERTERROR,e.getCause().getMessage(),i + 5);
                    }
                }

                //r中写入成功信息
                r.code(ResultCode.SUCCESS).message("插入成功");
            }
        }).headRowNumber(4).sheet().doRead();

        return r;
    }

    /**
     * 导出表格
     * @param response
     * @param condition
     * @return
     */
    @Override
    public R writeExcel(HttpServletResponse response, ResearchProjectRead researchProjectRead) {
        //从数据库中查询对应表格
        List<ResearchProjectRead> researchProjectReadList = researchProjectMapper.writeResearchProjectConditionalQuery(researchProjectRead);
        for (int i = 0; i < researchProjectReadList.size(); i++) {
            researchProjectReadList.get(i).setNum(i + 1);
        }

        //导出(匿名内部类SheetWriteHandler)
        response.addHeader("Content-Disposition", "attachment;fileName=下载案例5.xlsx");// 设置文件名
        try {
            EasyExcel.write(response.getOutputStream()).withTemplate(filePathConfig.writeExcelFilePath + "sheet05Template.xlsx").registerWriteHandler(new SheetWriteHandler() {

                @Override
                public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

                }

                @Override
                public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
                    //日志
                }


            }).sheet().doFill(researchProjectReadList);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.OK();
    }

    /**
     * 查询全部
     * @return
     */
    @Override
    public R selectAllResearchProjectInfo(int current,int limit) {
        //Page类的构造函数中第一个参数为当前查询第几页，第二个参数为每页的记录数(分页查询)
        Page<ResearchProjectRead> researchProjectReadPage = new Page<ResearchProjectRead>(current,limit);
        IPage<ResearchProjectRead> teacherPracticeReadIPage = researchProjectMapper.selectAllResearchProjectInfo(researchProjectReadPage);
        List<ResearchProjectRead> records = teacherPracticeReadIPage.getRecords();

        return R.OK().data("list",records).data("total",teacherPracticeReadIPage.getTotal()).data("pages",teacherPracticeReadIPage.getPages());
    }

    /**
     * 条件查询
     * @param s
     * @return
     */
    @Override
    public R researchProjectConditionalQuery(String s,int current,int limit) {
        Page<ResearchProjectRead> researchProjectReadPage = new Page<ResearchProjectRead>(current,limit);
        ResearchProjectRead researchProjectRead = JSONObject.parseObject(s, ResearchProjectRead.class);
        IPage<ResearchProjectRead> researchProjectReadIPage = researchProjectMapper.researchProjectConditionalQuery(researchProjectReadPage, researchProjectRead);
        List<ResearchProjectRead> records = researchProjectReadIPage.getRecords();
        return records.size() != 0 ? R.OK().data("list",records) : R.OK().message("您所查询的信息不存在").data("list",records);
    }

    /**
     * 更新
     * @param researchProjectCondition
     * @return
     */
    @Override
    public R updateResearchProjectInfo(String researchProjectCondition) {
        //Json转换
        ResearchProjectRead researchProjectRead = JSONObject.parseObject(researchProjectCondition, ResearchProjectRead.class);
        ResearchProject researchProject = new ResearchProject();
        //复制属性
        BeanUtils.copyProperties(researchProjectRead,researchProject);

        //构造条件
        QueryWrapper<ResearchProject> researchProjectQueryWrapper = new QueryWrapper<ResearchProject>();
        researchProjectQueryWrapper.eq("research_project_id",researchProject.getResearchProjectId());

        //返回数值1
        int update = researchProjectMapper.update(researchProject, researchProjectQueryWrapper);

        return update == 1 ? R.OK().message(researchProjectRead.getId() + "修改成功") : R.ERROR().code(ResultCode.UPDATEERROR).message(researchProject.getId() + "修改失败");
    }

    /**
     * 删除信息
     * @param id
     * @return
     */
    @Override
    public R deleteResearchProjectById(String id) {
        int id1 = researchProjectMapper.delete(new QueryWrapper<ResearchProject>().eq("research_project_id", id));
        return id1 == 1 ? R.OK().message("删除成功") : R.ERROR().code(ResultCode.DELETEERROR).message("删除失败");
    }

    /**
     * 增加
     * @param researchProject
     * @return
     */
    @Override
    public R insertResearchProjectInfo(ResearchProject researchProject) {
        researchProjectMapper.insert(researchProject);

//        try {
//        } catch (RuntimeException e) {
//            throw new YGException(ResultCode.INSERTERROR,e.getCause().getMessage(),1);
//        }
        return R.OK().message("成功");
    }

    /**
     * 查询字典表
     * @return
     */
    public Map<String, List<Dictionary>> getDictionary(){
        //查询
        List<Dictionary> title = dictionaryMapper.selectList(new QueryWrapper<Dictionary>().eq("english_name", "title").orderByAsc("sort"));

        Map<String,List<Dictionary>> stringListMap = new HashMap<>();
        stringListMap.put("title",title);
        return stringListMap;
    }

}
